package com.zym.application.controller.tms.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zym.application.column.BaseData;
import com.zym.application.config.SystemConfig;
import com.zym.application.controller.tms.shipment.TmsShipmentController;
import com.zym.application.model.ReturnModel;
import com.zym.application.session.Http;
import com.zym.application.session.HttpCall;
import com.zym.application.utils.StringUtils;
import com.zym.framework.alert.AlertUtils;
import com.zym.framework.combobox.ZymComboBox;
import com.zym.framework.form.ZymCallBack;
import com.zym.framework.form.ZymForm;
import com.zym.framework.grid.ZymGrid;
import com.zym.framework.notice.NoticeUtils;
import com.zym.framework.utlis.FxmlUtil;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.util.Callback;
import javafx.util.StringConverter;

import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * QQ 165149324
 * 臧英明
 *
 * @author
 * @create 2021-02-05
 */
public class TmsOrderController implements Initializable {
    @FXML
    public ZymComboBox select;
    @FXML
    public ZymComboBox age3;
    @FXML
    public ZymComboBox age2;
    @FXML
    public ZymComboBox age1;
    @FXML
    public CheckBox s2;
    @FXML
    public CheckBox s3;
    @FXML
    public CheckBox s4;
    @FXML
    public CheckBox s5;
    @FXML
    public CheckBox s6;
    @FXML
    public CheckBox s7;
    @FXML
    public DatePicker times1;
    @FXML
    public DatePicker times2;
    @FXML
    public DatePicker times4;
    @FXML
    public DatePicker times3;
    private FXMLLoader fxmlLoader;
    private ZymGrid zymGrid;
    @FXML
    private SplitPane splitPane;
    private String fromXmlPath = "/view/tms/order/tms-order-from.fxml";
    private ZymForm zymForm;
    private TmsOrderFromController controller;
    @FXML
    private TextField itemName;

    private TmsShipmentController tmsShipmentController;
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        this.fxmlLoader = ZymGrid.create();
        this.zymGrid = fxmlLoader.getController();
        Map databook = new HashMap();
        databook.put("TASK","Istrue");
        databook.put("DELIVER","Istrue");
        databook.put("STATE","TmsOrderType");
        databook.put("TRACK_MODEL","TrackModel");
        databook.put("TRANSPORT_TYPE","TransportType");
        databook.put("LTL","LTL");
        zymGrid.initView("/tmsorder/list",BaseData.TMS_ORDER,databook);
        zymGrid.setWinHeight(630);

        Parent root = this.fxmlLoader.getRoot();
        splitPane.getItems().add(root);
        this.zymForm = new ZymForm("/tmsorder/save","/tmsorder/get",fromXmlPath,"订单管理");
        controller = zymForm.getController(TmsOrderFromController.class);
        zymForm.setFormCallback(new ZymCallBack() {
            @Override
            public void submitStart(JSONObject jsonObject) {
                List cledgerItems = controller.getCledgerItems();
                List productItems = controller.getProductItems();
                List sledgerItems = controller.getSledgerItems();
                if(productItems.size() == 0){ //后台设计 不传报错
                    JSONObject product = new JSONObject();
                    product.put("CODE","");
                    product.put("NUMBER","0.0");
                    product.put("ROUGT_WEIGHT","0.0");
                    product.put("VOLUME","0.0");
                    product.put("NET_WEIGHT","0.0");
                    product.put("VALUE","0.0");
                    productItems.add(product);
                }else {
                    for (int i = 0; i < productItems.size(); i++) {
                        Map map = (Map) productItems.get(i);
                        map.remove("SYS_ORG_ID");
                    }
                }
                if(cledgerItems.size() == 0){ //后台设计 不传报错
                    JSONObject ledger = new JSONObject();
                    ledger.put("BASE_COST_MANAGE_ID",null);
                    ledger.put("AMOUNT","0.0");
                    ledger.put("TAXRATE","0.0");
                    ledger.put("INPUT","0.0");
                    cledgerItems.add(ledger);
                }
                if(sledgerItems.size() == 0){ //后台设计 不传报错
                    JSONObject ledger = new JSONObject();
                    ledger.put("BASE_COST_MANAGE_ID",null);
                    ledger.put("AMOUNT","0.0");
                    ledger.put("TAXRATE","0.0");
                    ledger.put("INPUT","0.0");
                    sledgerItems.add(ledger);
                }
                jsonObject.put("jsonBeans",productItems);
                jsonObject.put("jsonBeans2",sledgerItems);
                jsonObject.put("jsonBeans3",cledgerItems);
            }
            @Override
            public void submitEnd() {
                queryList();
            }
            @Override
            public void getStart(Map map){
                JSONObject jsonObject = new JSONObject(map);
                JSONObject bean = jsonObject.getJSONObject("bean");
                JSONArray cList = jsonObject.getJSONArray("cList");
                JSONArray sList = jsonObject.getJSONArray("sList");
                JSONArray products = jsonObject.getJSONArray("products");
                int order_audit = SystemConfig.getInstance().getOrgConfig().getIntValue("ORDER_AUDIT");
                int state = bean.getIntValue("STATE");
                if(order_audit <=state){
                    controller.lockFrom(true);
                    zymForm.lockSaveButton(true);
                }else {
                    controller.lockFrom(false);
                    zymForm.lockSaveButton(false);
                }
//                if(this.bean.STATE <   this.$store.state.app.tmsSystem.ORDER_AUDIT){
//                    this.view=false
//                }else {
//                    this.view=true
//                }
                map.clear();
                map.putAll(bean);
                controller.setCledgerItems(cList);
                controller.setProductItems(products);
                controller.setSledgerItems(sList);
            }
        });
        zymGrid.setRowFactory(new Callback<TableView, TableRow>() {
            @Override
            public TableRow call(TableView param) {
                TableRow<JSONObject> row = new TableRow<JSONObject>();
                row.setOnMouseClicked(event -> {
                    if (event.getClickCount() == 2 && (! row.isEmpty()) ) {
                        JSONObject jsonObject = row.getItem();
                        String id = jsonObject.getString("ID");
                        zymForm.open(id);
                    }
                });
                return row ;
            }
        });
        select.getItems().setAll( zymGrid.getSelectModels());
        select.initValue();
        s2.setSelected(true);
        s3.setSelected(true);
        s4.setSelected(true);
        StringConverter converter = new StringConverter<LocalDate>() {
            DateTimeFormatter dateFormatter =
                    DateTimeFormatter.ofPattern("yyyy-MM-dd");
            @Override
            public String toString(LocalDate date) {
                if (date != null) {
                    return dateFormatter.format(date);
                } else {
                    return "";
                }
            }
            @Override
            public LocalDate fromString(String string) {
                if (string != null && !string.isEmpty()) {
                    return LocalDate.parse(string, dateFormatter);
                } else {
                    return null;
                }
            }
        };
        times1.setConverter(converter);
        times2.setConverter(converter);
        times3.setConverter(converter);
        times4.setConverter(converter);
    }


    public void queryList(){
        Map map= new HashMap();
        if(StringUtils.isNotEmpty(itemName.getText())){
            map.put("sqlWhereNameToLike",select.getValue().getId());
            map.put("sqlWhereValueToLike",itemName.getText());
        }
        if(age1.getValue()!=null && StringUtils.isNotEmpty(age1.getValue().getId())){
            map.put("age1",age1.getValue().getId());
        }
        if(age2.getValue()!=null &&StringUtils.isNotEmpty(age2.getValue().getId())){
            map.put("age2",age2.getValue().getId());
        }
        if(age3.getValue()!=null &&StringUtils.isNotEmpty(age3.getValue().getId())){
            map.put("age3",age3.getValue().getId());
        }
        List ids = new ArrayList();
        if(s2.isSelected()){
            ids.add("2");
        }
        if(s3.isSelected()){
            ids.add("3");
        }
        if(s4.isSelected()){
            ids.add("4");
        }
        if(s5.isSelected()){
            ids.add("5");
        }
        if(s6.isSelected()){
            ids.add("6");
        }
        if(s7.isSelected()){
            ids.add("7");
        }
        map.put("ids",ids);
        map.put("timeName","TIME");
        String text1 = times1.getEditor().getText();
        String text2 = times2.getEditor().getText();
        String text3 = times3.getEditor().getText();
        String text4 = times4.getEditor().getText();
        List time = new ArrayList();
        List time2 = new ArrayList();
        time.add(StringUtils.isNotEmpty(text1)?text1+"T16:00:00.000Z":null);
        time.add(StringUtils.isNotEmpty(text2)?text2+"T16:00:00.000Z":null);
        time2.add(StringUtils.isNotEmpty(text3)?text3+"T16:00:00.000Z":null);
        time2.add(StringUtils.isNotEmpty(text4)?text4+"T16:00:00.000Z":null);
        map.put("times",time);
        map.put("times2",time2);
        zymGrid.query(map);
    }
    public void open(){
        controller.lockFrom(false);
        zymForm.lockSaveButton(false);
        TmsOrderFromController controller = zymForm.getController(TmsOrderFromController.class);
        zymForm.open(null);
        controller.reset();
    }

    public void del(){
        List<String>  ids= zymGrid.getSelectId();
        if(ids.size() == 0){
            NoticeUtils.error("请勾选要更改的数据");
            return;
        }
        String str = "条数据执行删除？";
        if(!AlertUtils.confirmYesNoConfirmation("通知","您确定要对这"+ids.size()+str)){
            return;
        }
        JSONObject par = new JSONObject();
        par.put("ids",ids);
        Http.post("/tmsorder/delete", par, new HttpCall() {
            @Override
            public void exe(ReturnModel returnModel) {
                if (returnModel.isSuceess()){
                    NoticeUtils.success(returnModel.getObj().toString());
                    queryList();
                }else {
                    NoticeUtils.error(returnModel.getObj().toString());
                }

            }
        });
    }
    public void copyOrder(){
        List<String>  ids= zymGrid.getSelectId();
        if(ids.size() == 0){
            NoticeUtils.error("请勾选要更改的数据");
            return;
        }
        String str = "条数据执行复制？";
        if(!AlertUtils.confirmYesNoConfirmation("通知","您确定要对这"+ids.size()+str)){
            return;
        }
        JSONObject par = new JSONObject();
        par.put("ids",ids);
        Http.post("/tmsorder/copyOrder", par, new HttpCall() {
            @Override
            public void exe(ReturnModel returnModel) {
                if (returnModel.isSuceess()){
                    NoticeUtils.success(returnModel.getObj().toString());
                    queryList();
                }else {
                    NoticeUtils.error(returnModel.getObj().toString());
                }

            }
        });
    }
    public void audit(){
        List<String>  ids= zymGrid.getSelectId();
        if(ids.size() == 0){
            NoticeUtils.error("请勾选要更改的数据");
            return;
        }
        String str = "条数据审核？";
        if(!AlertUtils.confirmYesNoConfirmation("通知","您确定要对这"+ids.size()+str)){
            return;
        }
        JSONObject par = new JSONObject();
        par.put("ids",ids);
        Http.post("/tmsorder/audit", par, new HttpCall() {
            @Override
            public void exe(ReturnModel returnModel) {
                if (returnModel.isSuceess()){
                    NoticeUtils.success(returnModel.getObj().toString());
                    queryList();
                }else {
                    NoticeUtils.error(returnModel.getObj().toString());
                }
            }
        });
    }
    public void unAudit(){
        List<String>  ids= zymGrid.getSelectId();
        if(ids.size() == 0){
            NoticeUtils.error("请勾选要更改的数据");
            return;
        }
        String str = "条数据反审核？";
        if(!AlertUtils.confirmYesNoConfirmation("通知","您确定要对这"+ids.size()+str)){
            return;
        }
        JSONObject par = new JSONObject();
        par.put("ids",ids);
        Http.post("/tmsorder/unaudit", par, new HttpCall() {
            @Override
            public void exe(ReturnModel returnModel) {
                if (returnModel.isSuceess()){
                    NoticeUtils.success(returnModel.getObj().toString());
                    queryList();
                }else {
                    NoticeUtils.error(returnModel.getObj().toString());
                }
            }
        });
    }


    public void task(ActionEvent actionEvent) {
        if(this.tmsShipmentController == null){
            FXMLLoader fxmlLoader = FxmlUtil.loadFxmlFromResource("/view/tms/shipment/tms-shipment.fxml");
            this.tmsShipmentController = fxmlLoader.getController();
        }
        List<JSONObject> ids= zymGrid.getSelectData();
        List<JSONObject> data = new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            JSONObject jsonObject = ids.get(i);
            if(jsonObject.getIntValue("STATE") == 3){
                data.add(jsonObject);
            }
        }
        if(data.size() == 0){
            NoticeUtils.error("没有需要发运的数据");
            return;
        }
        this.tmsShipmentController.open(data,this);
    }

}
